﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ThinhTien.Common.Enums;
using DevExpress.Web.Mvc;
using ThinhTien.Data.Repository;
using ThinhTien.Models;
using DevExpress.Web.ASPxUploadControl;
using ThinhTien.Common;
using ThinhTien.Data;

namespace ThinhTien.Admin.Controllers
{
    public class ProductController : BaseController
    {
        //
        // GET: /Products/

        private ProductRepository product = new ProductRepository();

        public ActionResult Index()
        {
            Session["MenuItem"] = MenuItems.Product;
            return View();
        }

        #region Paging

        public ActionResult ProductRowPartial()
        {
            var viewModel = GridViewExtension.GetViewModel("gvProduct");
            if (viewModel == null)
            {
                viewModel = CreateGridViewModel();
            }
            return CustomBindingCore(viewModel);
        }

        public ActionResult ApplyFilterExpressionPartial(string filterExpression)
        {
            var viewModel = GridViewExtension.GetViewModel("gvProduct");
            viewModel.FilterExpression = filterExpression;
            return CustomBindingCore(viewModel);
        }

        public ActionResult ProductSortingRowPartial(GridViewColumnState column, bool reset)
        {
            var viewModel = GridViewExtension.GetViewModel("gvProduct");

            viewModel.SortBy(column, reset);
            return CustomBindingCore(viewModel);
        }

        private GridViewModel CreateGridViewModel()
        {
            var viewModel = new GridViewModel();
            viewModel.KeyFieldName = "ID";
            viewModel.Columns.Add("CategoryID");
            viewModel.Columns.Add("Name");
            viewModel.Columns.Add("Description");
            viewModel.Columns.Add("DescriptionDetail");
            viewModel.Columns.Add("ImageID");
            viewModel.Columns.Add("Price");
            viewModel.Columns.Add("Viewing");
            viewModel.Columns.Add("Warranty");
            viewModel.Columns.Add("IsDeleted");
            viewModel.Columns.Add("CreatedDate");
            viewModel.Columns.Add("UpdatedDate");
            viewModel.Columns.Add("CreatedBy");
            viewModel.Columns.Add("UpdatedBy");
            return viewModel;
        }

        public ActionResult ProductPagingRowPartial(GridViewPagerState pager)
        {
            var viewModel = GridViewExtension.GetViewModel("gvProduct");
            viewModel.Pager.Assign(pager);
            return CustomBindingCore(viewModel);
        }

        public ActionResult ProductFilteringRowPartial(GridViewColumnState column)
        {
            var viewModel = GridViewExtension.GetViewModel("gvProduct");
            viewModel.Columns[column.FieldName].Assign(column);
            return CustomBindingCore(viewModel);
        }

        PartialViewResult CustomBindingCore(GridViewModel gridViewModel)
        {
            gridViewModel.ProcessCustomBinding(
                ProductBindingHandler.GetDataRowCount,
                ProductBindingHandler.GetData
            );
            return PartialView("ProductGridPartial", gridViewModel);
        }

        #endregion

        #region CRUD
        public ActionResult AddProduct(int? id)
        {
            var model = new ProductViewModel();
            if (id.HasValue)
            {
                model = product.GetProductById(id.Value);
            }
            else
            {
                model = new ProductViewModel()
                {
                    DescriptionDetail = "<table width='100%' border='1'><tr><td>test</td></tr></table>"
                };
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult AddProduct(ProductViewModel model, UploadedFile[] ucMultiFiles)
        {
            if (model.ProductImages != null)
            {
                for (int i = 0; i < model.ProductImages.Count; i++)
                {
                    ModelState.Remove(string.Format("ProductImages[{0}].ID", i));
                    ModelState.Remove(string.Format("ProductImages[{0}].IsDeleted", i));
                    ModelState.Remove("Action");
                }
            }

            ModelState.Remove("ID");
            ModelState.Remove("ProductID");
            ModelState.Remove("Action");

            if (ModelState.IsValid)
            {
                var images = new List<ImageViewModel>();
                foreach (var item in ucMultiFiles)
                {
                    if (item.ContentLength > 0)
                    {
                        images.Add(new ImageViewModel()
                        {
                            FileData = item.FileBytes,
                            Filename = item.FileName,
                            FileSize = (int)item.ContentLength
                        });
                    }
                }

                try
                {
                    model.DescriptionDetail = HtmlEditorExtension.GetHtml("DesciptionDetail");
                    if (model.ProductID.HasValue)
                    {
                        product.Update(model, images);
                    }
                    else
                    {
                        product.AddNew(model, images);
                    }
                }
                catch (Exception ex)
                {

                }
            }

            return RedirectToAction("Index");
        }

        public ActionResult DeleteProduct(UserViewModel model, string selectedIds)
        {
            if (!string.IsNullOrEmpty(selectedIds))
            {
                var ids = new List<int>();
                foreach (var item in selectedIds.Split(','))
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        ids.Add(Convert.ToInt32(item));
                    }
                }

                try
                {
                    if (ids.Count > 0)
                    {
                        product.Delete(ids);
                    }
                }
                catch (Exception ex)
                {

                }
            }

            return ProductRowPartial();
        }

        #endregion

        #region Partial
        public ActionResult DesciptionDetailPartial()
        {
            return PartialView("Partials/DesciptionDetailPartial");
        }
        #endregion

    }
}
